import React from 'react'
import { Routes, Route, useLocation, useNavigate } from 'react-router-dom'
import { useSocketStore } from './stores/socketStore'
import { useDeviceStore } from './stores/deviceStore'
import Header from './components/Header.tsx'
import HomePage from './pages/HomePage.tsx'
import SettingsPage from './pages/SettingsPage.tsx'
import VoiceInputPage from './pages/VoiceInputPage.tsx'
import ConnectionStatus from './components/ConnectionStatus.tsx'
import { ToastContainer } from './components/Toast.tsx'
import { cleanupLegacyStorageStates } from './utils/stateSync.ts'
import { shouldReRegisterDevice, validateDeviceId } from './utils/device.ts'
import LoginPage from './pages/LoginPage.tsx'
import { useEffect } from 'react'

function useAuthGuard() {
  const navigate = useNavigate()
  const location = useLocation()
  useEffect(() => {
    const token = localStorage.getItem('token')
    if (!token && location.pathname !== '/login') {
      navigate('/login', { replace: true })
    }
    if (token && location.pathname === '/login') {
      navigate('/', { replace: true })
    }
  }, [location, navigate])
}

const App: React.FC = () => {
  const { isConnected, connect, socket } = useSocketStore()
  const { deviceId, initializeDevice } = useDeviceStore()

  React.useEffect(() => {
    // 初始化应用
    const initApp = async () => {
      try {
        // 清理旧版本的不正确持久化状态
        cleanupLegacyStorageStates()
        
        // 检查设备ID是否需要重新注册
        if (deviceId) {
          const needsReRegister = await shouldReRegisterDevice();
          if (needsReRegister) {
            console.log('🔄 检测到设备需要重新注册');
            // 强制重新初始化设备
            if (isConnected && socket) {
              await (initializeDevice as any)(socket);
            }
          } else if (!validateDeviceId(deviceId)) {
            console.warn('⚠️ 设备ID格式无效，需要重新注册');
            if (isConnected && socket) {
              await (initializeDevice as any)(socket);
            }
          }
        } else if (isConnected && socket) {
          // 没有设备ID，进行初始化
          await (initializeDevice as any)(socket);
        }

        // 连接到服务器
        if (!isConnected) {
          connect()
        }
      } catch (error) {
        console.error('应用初始化失败:', error)
      }
    }

    initApp()

    // 页面可见性变化时处理连接
    const handleVisibilityChange = () => {
      if (document.hidden) {
        // 页面隐藏时保持连接，但可以降低心跳频率
      } else {
        // 页面显示时确保连接正常
        if (!isConnected) {
          connect()
        }
      }
    }

    document.addEventListener('visibilitychange', handleVisibilityChange)

    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange)
    }
  }, [isConnected, connect, deviceId, initializeDevice, socket])
  
  useAuthGuard()

  return (
    <div className="pb-20">
      <Header />
      <ConnectionStatus />
      <main className="max-w-md mx-auto">
        <Routes>
          <Route path="/login" element={<LoginPage />} />
          <Route path="/" element={<HomePage />} />
          <Route path="/settings" element={<SettingsPage />} />
          <Route path="/voice" element={<VoiceInputPage />} />
        </Routes>
      </main>
      <ToastContainer />
    </div>
  )
}

export default App
